import React, { useEffect, useRef, useState } from 'react'
import DetailContainer from '@/components/DetailContainer'
import Descriptions from '@/components/Descriptions'
import { Button, Empty, Form, message, Space, Table, Typography } from 'antd'
import { EditFormInline, EditFormVertical } from '@/components/CustomForm'
import {
  useFormBase,
  useFormCalc,
  useFormFabric,
  useFormColor,
  useFormUpload,
  useFabricDel,
  useColorDel,
  useFormPlanInfo,
} from '../useForm'
import { useForm } from 'antd/es/form/Form'
import { useNavigate, useSearchParams } from 'react-router-dom'
import './FormShare.less'
import {
  getProductPlanningByPlanNo,
  getSizeListByClassId,
  productSpuDevelopmentCreate,
  getProductColorPageList,
  getStyleInfoById,
  getStyleInfoByDesignCode,
  psdEditDevInfo,
  psdEditMeasureInfo,
  psdEditAssociatedFabric,
  psdEditColorInfo,
  psdEditPicture,
  getByTinyClassId,
  productSpuDevelopmenteditPlanInfo,
} from '@/api/goods'
import { type ITableData as ITableDataPlan } from '@/pages/Goods/Plan/types'
import { useAppSelector } from '@/store/hooks'
import { IColorListType, ITableDataColor, ProductPlanningVO, ProductSpuColorDetailVO } from '../types'
import { onValuesChange } from '@/utils/onValuesChange'
import useViewLogs from '@/hooks/useViewLogs'
import { OperationLogType } from '@/constant'
import LogsDrawer from '@/components/LogsDrawer'
import PermissionButton from '@/components/PermissionButton'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useSearchFabric from '@/hooks/useSearchFabric'
import useGetClassIds from '@/hooks/useGetClassIds'
import useGetProDevSeason from '@/hooks/useGetProDevSeason'
import { PlusOutlined } from '@ant-design/icons'
import EditTable from './EditTable'
const Index: React.FC = () => {
  const userInfo = useAppSelector((state) => state.user.user_info)
  const { classIdOptions } = useGetClassIds()
  const ProDevSeason = useGetProDevSeason()
  let ColorTimeout: ITimeoutType
  const devListOrigin: IDesListType = [
    { label: '款式名称', key: 'spuName', content: '-' },
    {
      label: '主供应商',
      key: 'mainSupplierVO',
      content: '-',
      format: (info) => info?.mainSupplierVO?.supplierName || '-',
    },
    { label: '工厂类型', key: 'factoryTypeCode', content: '-' },
    { label: '设计师/买手', key: 'designerName', content: '-' },
    { label: '商品系列', key: 'productSeries', content: '-', showKey: 'productSeries' },
    {
      label: '其他可生产供应商',
      key: 'otherSupplierVOList',
      content: '-',
      format: (info) => {
        return info?.otherSupplierVOList?.reduce((acc: string, item: any, index: number) => {
          return acc + (index === 0 ? '' : ',') + item.supplierName
        }, '')
      },
    },
    {
      label: '尺码范围',
      key: 'sizeRangeList',
      content: '-',
      format: (info) => {
        return info?.sizeRangeList?.reduce((acc: string, item: any, index: number) => {
          return acc + (index === 0 ? '' : ',') + item.sizeDetailName
        }, '')
      },
    },
    { label: '基码', key: 'baseSizeName', content: '-', showKey: 'baseSizeCode' },
    { label: '版型', key: 'patternType', content: '-', showKey: 'patternType' },
    { label: '领型', key: 'collarType', content: '-', showKey: 'collarType' },
    { label: '花型', key: 'flowerType', content: '-', showKey: 'flowerType' },
    { label: '杯型', key: 'moduleType', content: '-', showKey: 'moduleType' },
    { label: '后比', key: 'laterThan', content: '-', showKey: 'laterThan' },
    { label: '模杯材质', key: 'moldCupMaterial', content: '-', showKey: 'moldCupMaterial' },
    { label: '模杯厚度', key: 'moldCupThickness', content: '-', showKey: 'moldCupThickness' },
    { label: '模杯形状', key: 'moldCupShape', content: '-', showKey: 'moldCupShape' },
    { label: '排扣', key: 'breasted', content: '-', showKey: 'breasted' },
    { label: '功能', key: 'functionType', content: '-', showKey: 'functionType' },
    { label: '风格', key: 'styleCode', content: '-', showKey: 'styleCode' },
    { label: '图案布局', key: 'patternLayoutCode', content: '-', showKey: 'patternLayoutCode' },
    { label: '元素', key: 'elementCode', content: '-', showKey: 'elementCode' },
    { label: '工艺', key: 'technicsCode', content: '-', showKey: 'technicsCode' },
    { label: '面料', key: 'fabricType', content: '-', showKey: 'fabricType' },
    { label: '适卖温度', key: 'sellTempCode', content: '-', showKey: 'sellTempCode' },
    { label: '克重', key: 'gramWeight', content: '-', showKey: 'gramWeight' },
    { label: '厚度', key: 'thicknessCode', content: '-', showKey: 'thicknessCode' },
    { label: '年龄段', key: 'ageCode', content: '-', showKey: 'ageCode' },
    { label: '款式成本', key: 'spuCost', content: '-', showKey: 'spuCost' },
    {
      label: '实际毛利率',
      key: 'realProfitRate',
      content: '-',
      format: (info) => (info.realProfitRate ? info.realProfitRate + '%' : '-'),
    },
    { label: '厂家款号', key: 'factorySpuCode', content: '-' },
  ]
  const [FormStyle] = useForm()
  const [ispedding, setispedding] = useState<boolean>(false)
  const [detailInfo, setDetail] = useState<Record<string, any>>({})
  const [detailDevInfo, setdetailDevInfo] = useState<Record<string, any>>({})
  const [productTemplateVO, setproductTemplateVO] = useState<IGoodsTemplateType>(null)
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [canEdit, setcanEdit] = useState(false)
  const [desInfoList, setDesInfoList] = useState<IDesListType>([
    {
      label: '设计编码',
      key: 'designCode',
      content: '-',
    },
    { label: '款式编码', key: 'spuCode', content: '-' },
    {
      label: '采购方式',
      key: 'purchaseType',
      content: '-',
      format: (info) => (info?.purchaseType == 1 ? '现采' : info?.purchaseType == 0 ? '集采' : '-'),
    },
  ])
  //基础信息
  const [planList, setplanList] = useState<IDesListType>([
    { label: '开发季', key: 'devSeasonName', content: '-' },
    {
      label: '款式分类',
      key: 'classId',
      content: '-',
      format: (rows) => {
        return rows?.className
          ? rows.className
          : (rows.bigClassName ? rows.bigClassName : '') +
              (rows.midClassName ? '-' + rows.midClassName : '') +
              (rows.smallClassName ? '-' + rows.smallClassName : '') +
              (rows.tinyClassName ? '-' + rows.tinyClassName : '')
      },
    },
    { label: '适销季节', key: 'seasonCodeName', content: '-' },
    { label: '企划SKC数量', key: 'skcPlanNum', content: '-' },
    { label: '上市日期', key: 'releaseSeasonDateStr', content: '-' },
    { label: '过季日期', key: 'overSeasonDateStr', content: '-' },
    { label: '企划毛利率', key: 'planRateStr', content: '-' },
    { label: '毛利率下限', key: 'profitRateLowerLimitStr', content: '-' },
    { label: '吊牌价', key: 'originSalePrice', content: '-' },
    { label: '价格带', key: 'priceTagCode', content: '-' },
    { label: '商品描述', key: 'productDesc', content: '-' },
    { label: '适销年龄段', key: 'suitAgeGroupName', content: '-' },
    { label: '商品等级', key: 'productLevelName', content: '-' },
    { label: '季节分组', key: 'seasonGroupName', content: '-' },
    { label: '价格属性', key: 'pricePropertyName', content: '-' },
    { label: '定价权限', key: 'priceAuthName', content: '-' },
    { label: '开发定位', key: 'devLocationName', content: '-' },
  ])
  //基础信息
  // const [noplanList, setnoplanList] = useState<IDesListType>([
  //   { label: '开发季', key: 'devSeasonName', content: '-' },
  //   {
  //     label: '款式分类',
  //     key: 'classId',
  //     content: '-',
  //     format: (rows) => {
  //       return (
  //         (rows.bigClassName ? rows.bigClassName : '') +
  //         (rows.midClassName ? '-' + rows.midClassName : '') +
  //         (rows.smallClassName ? '-' + rows.smallClassName : '') +
  //         (rows.tinyClassName ? '-' + rows.tinyClassName : '')
  //       )
  //     },
  //   },
  // ])
  const [isdraftEdit, setisdraftEdit] = useState<boolean>(false)
  const [isdevListEdit, setisdevListEdit] = useState<boolean>(false)
  const [devList, setdevList] = useState<IDesListType>(devListOrigin)
  const [iscalcListEdit, setiscalcListEdit] = useState<boolean>(false)
  const [calcList, setcalcList] = useState<IDesListType>([
    { label: '外包方式', key: 'outPackageTypeCodeName', content: '-' },
    { label: '中包标识', key: 'midPackageTypeCodeName', content: '-' },
    { label: '包装方式', key: 'packageTypeCodeName', content: '-' },
    { label: '计量单位', key: 'weightUnitCodeName', content: '-' },
    { label: '内箱数', key: 'inPackageNum', content: '-' },
    { label: '外箱数', key: 'outPackageNum', content: '-' },
  ])
  //fabric
  const [isfabricEdit, setisfabricEdit] = useState<boolean>(false)
  //color
  const [iscolorEdit, setiscolorEdit] = useState<boolean>(false)
  //upload
  const [isuploadEdit, setisuploadEdit] = useState<boolean>(false)
  // 商品企划获取到数据后可以显示下面的内容
  const [isShow, setisShow] = useState<boolean>(false)
  // 日志
  const [query] = useSearchParams()
  const navigate = useNavigate()
  //主供应商
  const mainSupplierCode = Form.useWatch('mainSupplierCode', FormStyle)
  const sizeRange = Form.useWatch('sizeRange', FormStyle)
  const [SizeGroupOptions, setSizeGroupOptions] = useState<IOptionItem[]>([])
  //面料option
  // const [FabricOptions, setFabricOptions] = useState<IOptionItem[]>([])
  const { FabricOption, handleSearchFabric } = useSearchFabric()
  const [FabricList, setFabricList] = useState<any[]>([])
  //颜色option
  const [ColorOptions, setColorOptions] = useState<IOptionItem[]>([])
  const [ColorList, setColorList] = useState<IColorListType[]>([])
  const [hasSelectedColorIds, sethasSelectedColorIds] = useState<string[]>([])
  const { SupplierOption, handleSearchSupplier } = useSearchSupplier()
  const inputRef = useRef<any>(null)
  const { SupplierOption: SupplierOptionOther, handleSearchSupplier: handleSearchSupplierOther } = useSearchSupplier()
  // 处理方式 根据designCode的有无判断调用什么接口
  const spuDevId = query.get('spuDevId') || query.get('designCode')
  const designCode = query.get('designCode')
  const NoPlan = query.get('noplan') == '1'
  //现采草稿
  const isSpotDev = query.get('purchaseType') == '1'
  const REQUIRED_FIELDS = [
    'intensiveStatus',
    'useSite',
    'fabricName',
    'fabricSupplier',
    'fabricSpec',
    'fabricComposition',
    'fabricBreadth',
    'gramWeight',
  ]
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'spuDevId',
    OperationLogType.PRODUCTDEV,
  )
  useEffect(() => {
    if (spuDevId) {
      setisShow(true)
      getDevStyleDetail()
    } else {
      if (NoPlan) {
        setisShow(false)
      }
      setisdevListEdit(true)
      setiscalcListEdit(true)
      setisfabricEdit(true)
      setiscolorEdit(true)
      setisuploadEdit(true)
    }
  }, [])

  useEffect(() => {
    if (productTemplateVO && productTemplateVO?.notShow?.length > 0) {
      const filtertaginfoList = devListOrigin.filter((item) => !productTemplateVO?.notShow?.includes(item.showKey!))
      handleDetailFactory(filtertaginfoList, detailDevInfo, setdevList)
    } else {
      handleDetailFactory(devListOrigin, detailDevInfo, setdevList)
    }
  }, [detailDevInfo, productTemplateVO])

  const getDevStyleDetail = async () => {
    let res: IResponseDetail<ProductSpuColorDetailVO>
    if (!designCode) {
      // 根据spuDevId获取详情
      res = await getStyleInfoById<ProductSpuColorDetailVO>({ spuDevId })
    } else {
      // 根据designCode获取详情
      res = await getStyleInfoByDesignCode<ProductSpuColorDetailVO>({ designCode })
    }
    if (res.code === 200) {
      const details = res.data
      setdetailDevInfo(details)
      details?.designCode && (document.title = details.designCode)
      if (details?.planNo) {
        onPlanNoSearch(details.planNo, details)
      } else {
        if (details.classId) {
          getTemplateData(details.classId)
          getProductPresetConfigInfos(details.classId)
        }
        const mergedDetail: Record<string, any> = {
          ...details,
          devSeasonName: details?.seasonName,
          className: details?.className,
        }
        const planlist = planList?.map((item) => {
          if (!details?.planNo) {
            const index = planList.findIndex((item) => item.key === 'originSalePrice')
            if (index >= 0) {
              planList[index]['label'] = '预估吊牌价'
            }
          }
          if (typeof item.format === 'function') {
            return {
              ...item,
              content: item.format(mergedDetail),
            }
          } else {
            return {
              ...item,
              content: mergedDetail[item.key + ''] || '-',
            }
          }
        })
        setplanList(planlist)
      }
      handleDetailFactory(desInfoList, details, setDesInfoList)
      handleDetailFactory(calcList, details, setcalcList)
      FormStyle.setFieldsValue({
        ...details,
        seasonId: details.seasonId ? Number(details.seasonId) : null,
        classId: details?.classIdList || null,
        sizeRange: details?.sizeRangeList?.map((item: any) => item.sizeDetailId),
        otherSupplierCodeList: details?.otherSupplierCodeList ? details?.otherSupplierCodeList?.split(',') : null,
        functionType: details?.functionType ? details.functionType.split(',') : null,
      })
      // FabricList FabricOption处理
      const fabric_list =
        details?.spuFabricConfigVOS?.map((item: any, index: number) => {
          return {
            ...item,
            tempId: index + new Date().getTime(),
          }
        }) || []
      setFabricList([...fabric_list])
      // ColorList ColorOption处理
      if (details.spuColorDetailVOS && details.spuColorDetailVOS.length > 0) {
        const canEdit = details.spuColorDetailVOS.some((item: any) => item.status == 3)
        setcanEdit(canEdit)
        const optionsOfColor =
          details?.spuColorDetailVOS?.map((item: any) => {
            return {
              label: item.colorDetailName,
              code: item.colorCode,
              value: item.colorDetailId + '',
              rgbValue: item.rgbValue || '',
              picUrl: item?.picUrl,
              status: item.status,
              disabled: item.status == 3,
              colorType: item.colorType,
            }
          }) || []
        const hasSelectedColorIds =
          optionsOfColor?.filter((item: any) => item.status == 3)?.map((ite: any) => ite.value) || []
        sethasSelectedColorIds(hasSelectedColorIds || [])
        setColorOptions(optionsOfColor)
        setColorList(optionsOfColor)
        FormStyle.setFieldValue(
          'colorDetailIds',
          optionsOfColor?.map((item: any) => item.value),
        )
      }
      FormStyle.setFieldValue('mainPicFileId', details?.mainPicFileId || null)
      FormStyle.setFieldValue('otherPicFileIdList', details?.otherPicFileIdList || null)
    }
  }

  const handleDetailFactory = (
    sourceList: IDesListType,
    targetInfo: any,
    set: React.Dispatch<React.SetStateAction<IDesListType>>,
  ) => {
    const res = sourceList?.map((item) => {
      if (typeof item.format === 'function') {
        return {
          ...item,
          content: item.format(targetInfo),
        }
      } else {
        return {
          ...item,
          content: targetInfo[item.key + ''] || '-',
        }
      }
    })
    set(res)
  }
  const startEdit = async (
    setisEdit: React.Dispatch<React.SetStateAction<boolean>>,
    callback: (data?: any) => Promise<any>,
  ) => {
    setispedding(true)
    const res = await callback().finally(() => setispedding(false))
    if (res.code === 200) {
      setisEdit(false)
      message.success('操作成功')
      getDevStyleDetail()
    }
  }
  const newCreate = async () => {
    // 新建逻辑
    const data = await FormStyle.validateFields()
    //草稿 开发季和款式分类
    const draftObj = {
      classId:
        data.classId && data.classId.length === 4 ? data.classId[3] : detailInfo?.classId ? detailInfo?.classId : null,
      seasonId: data.seasonId ? data.seasonId : detailInfo?.seasonId ? detailInfo?.seasonId : null,
      seasonName: data.seasonId
        ? ProDevSeason?.find((item) => item.value == data.seasonId)?.label
        : detailInfo?.devSeasonName
        ? detailInfo.devSeasonName
        : null,
    } as Record<string, any>
    draftObj.purchaseType = isSpotDev ? 1 : 0
    const filterData = Object.fromEntries(Object.entries(data)?.filter(([_, val]) => val)) as Record<string, any>
    if (
      FabricList.some(
        (item) =>
          item?.intensiveStatus == 1 &&
          REQUIRED_FIELDS.some((field) => item?.[field] == undefined || item?.[field] === ''),
      )
    ) {
      message.warning('集约面料请填写完整面料信息！')
      return
    }
    if (FabricList.some((item) => item?.intensiveStatus == 0 && (!item?.useSite || !item?.fabricName))) {
      message.warning('非集约面料请填写使用部位和面料名称！')
      return
    }
    const newFabricList = FabricList?.map((item, index) => {
      const { tempId, isEdit, ...reset } = item
      return {
        ...reset,
        mainFabric: index === 0 ? 1 : 0,
      }
    })
    const params = {
      ...filterData,
      functionType: data.functionType ? data?.functionType?.join(',') : null,
      planingId: detailInfo?.planingId || '',
      priceTagCode: detailInfo?.priceTagCode || '',
      sizeRange: filterData.sizeRange && filterData.sizeRange.length > 0 ? filterData.sizeRange.join(',') : '',
      otherSupplierCodeList:
        filterData?.otherSupplierCodeList && filterData?.otherSupplierCodeList?.length > 0
          ? filterData?.otherSupplierCodeList.join(',')
          : '',
      colorDetails:
        ColorList?.map((item) => {
          return {
            colorDetailId: item.value,
            colorType: item.colorType,
          }
        }) || [],
      ...draftObj,
      productSpuFabricDTOS: newFabricList,
      originSalePrice: data?.originSalePrice || detailInfo?.originSalePrice,
    }
    setispedding(true)
    const res = await productSpuDevelopmentCreate(params).finally(() => setispedding(false))
    if (res.code === 200) {
      message.open({
        type: 'success',
        content: (
          <Typography.Text>
            {spuDevId ? '' : '新建'}款式{spuDevId ? '修改' : ''}成功，设计编码：
            <Typography.Link onClick={() => navigate('/goods/style/detail?designCode=' + res.data)}>
              {res.data}
            </Typography.Link>
          </Typography.Text>
        ),
        duration: 5,
      })
      navigate('/goods/style/list')
    }
  }
  const onPlanNoSearch = async (val: string, detailDevInfo?: Record<string, any>) => {
    const res = await getProductPlanningByPlanNo<ITableDataPlan>({ planNo: val })
    handleSearchSupplier()
    if (res.code === 200) {
      const details = res.data
      details.classId && getProductPresetConfigInfos(details.classId)
      details?.productTemplateVO && setproductTemplateVO(details.productTemplateVO)
      setDetail(details)
      setisShow(true)
      handleSearchFabric('', details?.devSeasonName, details?.bigClassId)
      const mergedDetail: Record<string, any> = {
        ...details,
        originSalePrice: detailDevInfo?.originSalePrice || details?.originSalePrice,
      }
      const planlist = planList?.map((item) => {
        if (typeof item.format === 'function') {
          return {
            ...item,
            content: item.format(mergedDetail),
          }
        } else {
          return {
            ...item,
            content: mergedDetail[item.key + ''] || '-',
          }
        }
      })
      setplanList(planlist)
    }
  }
  const getProductPresetConfigInfos = async (tinyClassId: number | string) => {
    const res = await getSizeListByClassId<{ sizeDetailId: number; sizeDetailName: string }>({ tinyClassId })
    if (res.code === 200) {
      const data =
        res?.data?.map((item) => {
          return {
            label: item.sizeDetailName,
            value: item.sizeDetailId,
          }
        }) || []
      setSizeGroupOptions(data)
    }
  }
  const handleSearchColor = (newValue = '') => {
    if (ColorTimeout) {
      clearTimeout(ColorTimeout)
      ColorTimeout = null
    }
    const getOptions = async () => {
      const res = await getProductColorPageList<ITableDataColor>({ colorGroupSearchName: newValue, enableStatus: 1 })
      if (res.code === 200) {
        const data =
          res?.data?.list
            ?.filter((it) => !hasSelectedColorIds.includes(it.colorDetailId + ''))
            ?.map((item) => {
              return {
                label: item.colorDetailName,
                code: item.colorCode,
                value: item.colorDetailId + '',
                rgbValue: item.rgbValue,
                picUrl: item?.picUrl,
              }
            }) || []
        const selectedList =
          ColorList?.filter((it) => it?.status == 3)?.map((item) => {
            return {
              ...item,
              disabled: true,
            }
          }) || []
        setColorOptions([...selectedList, ...data])
      }
    }
    ColorTimeout = setTimeout(getOptions, 500)
  }
  const onDelColor = (info: IOptionItem) => {
    const colorDetailIds = (FormStyle.getFieldValue('colorDetailIds') as number[]) || []
    if (colorDetailIds?.length === 1) {
      message.warning('最少保留一条款式色！')
      return
    }
    const resetcolorDetailIds = colorDetailIds?.filter((item) => item != info.value)
    FormStyle.setFieldValue('colorDetailIds', resetcolorDetailIds)
    const list = ColorList?.filter((item) => item.value != info.value)
    setColorList(list)
  }
  const handleColorChange = (_: number[], info: IColorListType[]) => {
    info?.forEach((item) => {
      ColorList?.forEach((it) => {
        if (item.value == it.value) {
          item.colorType = it?.colorType
        }
      })
    })
    setColorList([...info])
  }
  const onValuesFormChange = (changedValues: any) => {
    onValuesChange(
      changedValues,
      [
        'spuName',
        'productSeries',
        'patternType',
        'collarType',
        'flowerType',
        'moduleType',
        'fabricType',
        'factorySpuCode',
      ],
      FormStyle,
    )
  }
  const handleChangeClassId = async (val: any) => {
    if (!isdraftEdit) {
      if (val && val.length === 4) {
        await getTemplateData(val[3])
        getProductPresetConfigInfos(val[3])
        setisShow(true)
      } else {
        setisShow(false)
      }
    }
  }
  const getTemplateData = async (tinyClassId: number | string) => {
    const res = await getByTinyClassId({ tinyClassId })
    setproductTemplateVO(res?.data || null)
  }
  return (
    <DetailContainer
      className="goods_style_add_page"
      footer={
        <Space>
          {spuDevId && Object.keys(detailDevInfo).length > 0 && (
            <Button type="primary" ghost onClick={() => viewLogs(detailDevInfo)}>
              查看日志
            </Button>
          )}
          {!spuDevId && (
            <Button type="primary" onClick={() => newCreate()} loading={ispedding}>
              新建
            </Button>
          )}
        </Space>
      }
    >
      {isShow && spuDevId ? <Descriptions title="" list={desInfoList}></Descriptions> : null}
      <Descriptions
        title="企划信息"
        list={NoPlan || isdraftEdit ? [] : planList}
        extraHeader={
          !spuDevId &&
          !NoPlan && (
            <EditFormInline
              className="sep_forminline_style"
              onValuesChange={onValuesFormChange}
              editConfig={[
                {
                  name: 'planNo',
                  label: '商品企划编号',
                  type: 'Search',
                  placeholder: '请输入商品企划编号',
                  rules: [
                    {
                      required: true,
                      message: '请输入商品企划编号',
                    },
                  ],
                  config: {
                    onSearch: onPlanNoSearch,
                  },
                },
              ]}
              form={FormStyle}
            />
          )
        }
        extra={
          <Space>
            {spuDevId && !detailDevInfo?.planNo && (
              <PermissionButton
                permission="editDevBase"
                loading={ispedding}
                type="primary"
                onClick={async () => {
                  if (isdraftEdit) {
                    const params = await FormStyle.validateFields()
                    const devSeason = ProDevSeason.find((item) => item.value == params.seasonId)?.label
                    const data = {
                      classId: params.classId[3],
                      devSeasonId: params.seasonId,
                      devSeason,
                      originSalePrice: params.originSalePrice,
                      spuDevId: detailDevInfo?.spuDevId,
                    }
                    startEdit(setisdraftEdit, () => productSpuDevelopmenteditPlanInfo(data))
                  } else {
                    if (canEdit) {
                      message.warning('当前款式已被选中，请前往【商品-商品管理】页面更新相关信息')
                      return
                    }
                    setisdraftEdit(true)
                  }
                }}
              >
                {isdraftEdit ? '保存修改' : '编辑'}
              </PermissionButton>
            )}
            {spuDevId && isdraftEdit ? (
              <Button
                onClick={() => {
                  setisdraftEdit(false)
                  getDevStyleDetail()
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        {isShow || NoPlan ? (
          <EditFormInline
            className="sep_forminline_style"
            onValuesChange={onValuesFormChange}
            editConfig={useFormPlanInfo({
              ProDevSeason,
              classIdOptions,
              handleChangeClassId,
              showOriginSalePrice: NoPlan || isdraftEdit,
              isSpotDev,
              detailDevInfo,
            })}
            form={FormStyle}
          />
        ) : null}
      </Descriptions>
      {isShow ? (
        <Descriptions
          title="开发信息"
          list={isdevListEdit ? [] : devList}
          extra={
            <Space>
              {spuDevId && (
                <PermissionButton
                  permission="editDevBase"
                  loading={ispedding}
                  type="primary"
                  onClick={async () => {
                    if (isdevListEdit) {
                      const data = await FormStyle.validateFields()
                      const entries = Object.entries(data).map(([key, value]) => {
                        return [key, value === undefined ? '' : value]
                      })
                      const filterData = Object.fromEntries(entries) as Record<string, any>
                      const params = {
                        ...filterData,
                        functionType: data.functionType ? data?.functionType?.join(',') : null,
                        planingId: detailInfo?.planingId || '',
                        spuDevId: detailDevInfo?.spuDevId,
                        sizeRange: data.sizeRange && data.sizeRange.length > 0 ? data.sizeRange.join(',') : '',
                        otherSupplierCodeList:
                          data?.otherSupplierCodeList && data?.otherSupplierCodeList?.length > 0
                            ? data?.otherSupplierCodeList?.join(',')
                            : '',
                      }
                      startEdit(setisdevListEdit, () => psdEditDevInfo(params))
                    } else {
                      if (canEdit) {
                        message.warning('当前款式已被选中，请前往【商品-商品管理】页面更新相关信息')
                        return
                      }
                      setisdevListEdit(true)
                    }
                  }}
                >
                  {isdevListEdit ? '保存修改' : '编辑'}
                </PermissionButton>
              )}
              {spuDevId && isdevListEdit ? (
                <Button
                  onClick={() => {
                    setisdevListEdit(false)
                    getDevStyleDetail()
                  }}
                >
                  取消
                </Button>
              ) : null}
            </Space>
          }
        >
          <EditFormInline
            className="sep_forminline_style"
            onValuesChange={onValuesFormChange}
            editConfig={useFormBase({
              SupplierOption,
              handleSearchSupplier,
              SupplierOptionOther,
              handleSearchSupplierOther,
              DICTDATA,
              mainSupplierCode,
              sizeRange,
              SizeGroupOptions,
              FormStyle,
              productTemplateVO,
              detailInfo,
            })}
            form={FormStyle}
            initialValues={{ designerName: userInfo.userName || '' }}
          />
        </Descriptions>
      ) : null}
      {isShow ? (
        <Descriptions
          title="计量信息"
          list={iscalcListEdit ? [] : calcList}
          extra={
            <Space>
              {spuDevId && (
                <PermissionButton
                  permission="editDevMeasure"
                  loading={ispedding}
                  type="primary"
                  onClick={async () => {
                    if (iscalcListEdit) {
                      const data = await FormStyle.validateFields()
                      const params = {
                        ...data,
                        planingId: detailInfo?.planingId || '',
                        spuDevId: detailDevInfo?.spuDevId,
                      }
                      startEdit(setiscalcListEdit, () => psdEditMeasureInfo(params))
                    } else {
                      if (canEdit) {
                        message.warning('当前款式已被选中，请前往【商品-商品管理】页面更新相关信息')
                        return
                      }
                      setiscalcListEdit(true)
                    }
                  }}
                >
                  {iscalcListEdit ? '保存修改' : '编辑'}
                </PermissionButton>
              )}
              {spuDevId && iscalcListEdit ? (
                <Button
                  onClick={() => {
                    setiscalcListEdit(false)
                    getDevStyleDetail()
                  }}
                >
                  取消
                </Button>
              ) : null}
            </Space>
          }
        >
          <EditFormInline
            className="sep_forminline_style"
            editConfig={useFormCalc({ DICTDATA })}
            form={FormStyle}
            onValuesChange={onValuesFormChange}
            initialValues={{ outPackageTypeCode: '1号标箱(60*40*40)', midPackageTypeCode: '单色码' }}
          />
        </Descriptions>
      ) : null}
      {isShow ? (
        <Descriptions
          title="面料"
          extra={
            <Space>
              {spuDevId && (
                <PermissionButton
                  permission="editDevFabric"
                  loading={ispedding}
                  type="primary"
                  onClick={async () => {
                    if (isfabricEdit) {
                      if (
                        FabricList.some(
                          (item) =>
                            item?.intensiveStatus == 1 &&
                            REQUIRED_FIELDS.some((field) => item?.[field] == undefined || item?.[field] === ''),
                        )
                      ) {
                        message.warning('集约面料请填写完整面料信息！')
                        return
                      }
                      if (
                        FabricList.some((item) => item?.intensiveStatus == 0 && (!item?.useSite || !item?.fabricName))
                      ) {
                        message.warning('非集约面料请填写使用部位和面料名称！')
                        return
                      }
                      const newFabricList = FabricList?.map((item, index) => {
                        const { tempId, isEdit, ...reset } = item
                        return {
                          ...reset,
                          mainFabric: index === 0 ? 1 : 0,
                        }
                      })
                      const params = {
                        spuDevId: detailDevInfo?.spuDevId,
                        productSpuFabricDTOS: newFabricList,
                      }
                      startEdit(setisfabricEdit, () => psdEditAssociatedFabric(params))
                    } else {
                      if (canEdit) {
                        message.warning('当前款式已被选中，请前往【商品-商品管理】页面更新相关信息')
                        return
                      }
                      setisfabricEdit(true)
                    }
                  }}
                >
                  {isfabricEdit ? '保存修改' : '编辑'}
                </PermissionButton>
              )}
              {spuDevId && isfabricEdit ? (
                <Button
                  onClick={() => {
                    setisfabricEdit(false)
                    getDevStyleDetail()
                  }}
                >
                  取消
                </Button>
              ) : null}
            </Space>
          }
        >
          <div className="flex_column">
            <div className="custom_table_style style_fabricedit_wrap" style={{ width: 1200 }}>
              <EditTable
                columns={useFabricDel({
                  isEdit: isfabricEdit,
                  FabricList,
                  setFabricList,
                  FabricOption,
                  handleSearchFabric,
                  SupplierOption,
                  handleSearchSupplier,
                  detailDevInfo,
                  detailInfo,
                  inputRef,
                  FormStyle,
                  ProDevSeason,
                })}
                tableData={FabricList}
                settableData={setFabricList}
                showAddBtn={isfabricEdit}
              />
            </div>
          </div>
        </Descriptions>
      ) : null}
      {isShow ? (
        <Descriptions
          title="款式色"
          extra={
            <Space>
              {spuDevId && (
                <PermissionButton
                  permission="editDevSku"
                  loading={ispedding}
                  type="primary"
                  onClick={async () => {
                    if (iscolorEdit) {
                      const data = await FormStyle.validateFields()
                      const params = {
                        ...data,
                        planingId: detailInfo?.planingId || '',
                        spuDevId: detailDevInfo?.spuDevId,
                        colorDetails:
                          ColorList?.map((item) => {
                            return {
                              colorDetailId: item.value,
                              colorType: item.colorType,
                            }
                          }) || [],
                      }
                      startEdit(setiscolorEdit, () => psdEditColorInfo(params))
                    } else {
                      setiscolorEdit(true)
                    }
                  }}
                >
                  {iscolorEdit ? '保存修改' : '编辑'}
                </PermissionButton>
              )}
              {spuDevId && iscolorEdit ? (
                <Button
                  onClick={() => {
                    setiscolorEdit(false)
                    getDevStyleDetail()
                  }}
                >
                  取消
                </Button>
              ) : null}
            </Space>
          }
        >
          <div className="flex_column">
            <EditFormVertical
              className="fc_width_limit"
              editConfig={useFormColor({
                isEdit: iscolorEdit,
                handleColorChange,
                ColorOptions,
                handleSearchColor,
              })}
              onValuesChange={onValuesFormChange}
              form={FormStyle}
              initialValues={{ colorDetailIds: [] }}
            />
            <div className="custom_table_style width_limit_wrap">
              <Table
                bordered
                columns={useColorDel({ isEdit: iscolorEdit, onDelColor, ColorList, setColorList })}
                dataSource={ColorList}
                rowKey="value"
                scroll={{ y: 400 }}
                pagination={false}
                rowHoverable={false}
                rowClassName={(_, index) => {
                  return index % 2 === 0 ? '' : 'zebra-row-odd'
                }}
              />
            </div>
          </div>
        </Descriptions>
      ) : null}
      {isShow ? (
        <Descriptions
          title="款式图"
          extra={
            <Space>
              {spuDevId && (
                <PermissionButton
                  permission="editDevPicture"
                  loading={ispedding}
                  type="primary"
                  onClick={async () => {
                    if (isuploadEdit) {
                      const data = await FormStyle.validateFields()
                      const params = {
                        mainPicFileId: data.mainPicFileId,
                        otherPicFileIdList: data.otherPicFileIdList,
                        planingId: detailInfo?.planingId || '',
                        spuDevId: detailDevInfo?.spuDevId,
                      }
                      startEdit(setisuploadEdit, () => psdEditPicture(params))
                    } else {
                      if (canEdit) {
                        message.warning('当前款式已被选中，请前往【商品-商品管理】页面更新相关信息')
                        return
                      }
                      setisuploadEdit(true)
                    }
                  }}
                >
                  {isuploadEdit ? '保存修改' : '编辑'}
                </PermissionButton>
              )}
              {spuDevId && isuploadEdit ? (
                <Button
                  onClick={() => {
                    setisuploadEdit(false)
                    getDevStyleDetail()
                  }}
                >
                  取消
                </Button>
              ) : null}
            </Space>
          }
        >
          <EditFormVertical
            editConfig={useFormUpload({ isEdit: isuploadEdit })}
            form={FormStyle}
            onValuesChange={onValuesFormChange}
          />
        </Descriptions>
      ) : null}
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
    </DetailContainer>
  )
}
export default Index
